package www.study.com;

//字符串转换整数 (atoi) https://leetcode.cn/problems/string-to-integer-atoi/
public class code8 {
    public static void main(String[] args) {

    }

    /**
     * 细节题，需要考虑特殊案例，如s为""、"    "，"-"，“+123”,"   +",“-12142354124314”等，防止越界，超过Integer表征的范围
     */
    class Solution {
        public int myAtoi(String s) {
            if(s == null || s.length() == 0) return 0; // ""
            s = s.trim();
            if(s == null || s.length() == 0) return 0; //"   "
            char[] chs = s.toCharArray();
            int index = 0;
            boolean up = true;
            if(chs[index] == '-'){
                index++;
                up = false;
            }else if(chs[index] == '+'){ //"+12"
                index++;
            }
            if(index < chs.length && isNumber(chs[index])){ //"-","+"
                long res = 0;
                while(index < chs.length && isNumber(chs[index])){
                    res = res * 10 + chs[index] - '0';
                    long temp = res * (up ? 1 : -1);
                    if(temp >= Integer.MAX_VALUE || temp <= Integer.MIN_VALUE){ //"-12425324253424"
                        res = up ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                        return (int)res;
                    }
                    index++;
                }
                return (int)res * (up ? 1 : -1);
            }else{
                return 0;
            }
        }
        public boolean isNumber(char c){ //c是否为数字字符
            return (c >= '0' && c <= '9');
        }
    }
}
